<template>
  <div>
    <el-row style="padding-bottom: 20px;">
      <el-col :span="3.5">
        <span>进度状态：</span>
        <el-select
          style="width: 80px;marginRight: 10px"
          v-model="form.scheduleStatus"
          placeholder="请选择"
          clearable
          collapse-tags
          @change="selectChange"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="3.5">
        <span>任务状态：</span>
        <el-select
          style="width: 80px;marginRight: 10px"
          v-model="form.taskStatus"
          placeholder="请选择"
          clearable
          collapse-tags
          @change="selectChange"
        >
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="3.5">
        <span>关键词：</span>
        <el-input
          style="width: 100px;marginRight: 10px"
          v-model="form.keyward"
          clearable
          placeholder="请输入"
        />
      </el-col>
      <el-col :span="5.9">
        <span>时间：</span>
        <el-date-picker
          style="width: 240px"
          v-model="form.picker"
          type="daterange"
          clearable
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-col>
      <input
        id="table1"
        type="file"
        accept=".xlsx, .xls"
        style="display:none"
        @change="handleFileUpload"
      />
      <el-col :span="7">
        <el-button type="primary" style="marginLeft: 5px;" @click="submitForm">搜索</el-button>
        <el-button type="primary" @click="resetForm">重置</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
        <el-button type="primary" @click="clickBtn">导入</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData" border :row-key="row => row._id">
      <!-- <el-table-column type="index" label="窗口索引" width="55" /> -->
      <el-table-column prop="index" label="窗口索引"  width="80" :showOverflowTooltip="true" /> 
      <el-table-column prop="containerIp" label="树Ip" :showOverflowTooltip="true" />
      <el-table-column prop="containerId" label="树名称" :showOverflowTooltip="true" />
      <el-table-column prop="vpnIp" label="节点" :showOverflowTooltip="true" />
      <el-table-column prop="emailUsername" label="邮箱账号" :showOverflowTooltip="true" />
      <el-table-column prop="emailPassword" label="邮箱密码" :showOverflowTooltip="true" />
      <el-table-column prop="emailPassword" label="辅助邮箱" :showOverflowTooltip="true" />
      <el-table-column prop="tiktokUsername" label="Tk用户名" :showOverflowTooltip="true" />
      <el-table-column prop="tiktokPasswd" label="Tk密码" :showOverflowTooltip="true" />
      <el-table-column prop="" label="粉丝数" :showOverflowTooltip="true" />
      <el-table-column prop="" label="关注数" :showOverflowTooltip="true" />
      <el-table-column prop="" label="点赞数" :showOverflowTooltip="true" />
      <el-table-column prop="statusText" label="任务信息" />
      <!-- <el-table-column prop="tiktokUsername" label="tk用户名" :showOverflowTooltip="true" />
      <el-table-column prop="tiktokPasswd" label="抖音密码" :showOverflowTooltip="true" />
      <el-table-column prop="emailUsername" label="邮箱帐号" :showOverflowTooltip="true" />
      <el-table-column prop="emailPassword" label="邮箱密码" :showOverflowTooltip="true" />
      <el-table-column prop="brand" label="品牌" :showOverflowTooltip="true" />
      <el-table-column prop="model" label="型号" :showOverflowTooltip="true" />
      <el-table-column prop="vpnPlatName" label="vpn平台" :showOverflowTooltip="true" />
      <el-table-column prop="startTimeStr" label="开始时间" :showOverflowTooltip="true" />
      <el-table-column prop="endTimeStr" label="结束时间" :showOverflowTooltip="true" />
      <el-table-column prop="statusText" label="任务信息" />-->
      <el-table-column prop="scheduleStatus" label="进度状态"> 
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.scheduleStatus === 'TODO'">未开始</el-tag>
          <el-tag type="warning" v-if="scope.row.scheduleStatus === 'DOING'">进行中</el-tag>
          <el-tag type="success" v-if="scope.row.scheduleStatus === 'DONE'">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" /> 
      <!-- <el-table-column prop="taskStatus" label="任务状态"/> -->
        <!-- <template slot-scope="scope">
          <el-tag v-if="scope.row.taskStatus === 'success'">成功</el-tag>
          <el-tag v-else-if="scope.row.taskStatus === 'error'">失败</el-tag>
          <el-tag v-else type="danger">未知</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-link
            type="primary"
            :disabled="!scope.row.taskId"
            @click="handleLog(scope.row.taskId)"
          >详情</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import moment from "moment";
import axios from "axios";
import * as XLSX from "xlsx";
export default {
  props: ["selectValue"],
  data() {
    return {
      form: {
        scheduleStatus: "",
        taskStatus: "",
        keyward: "",
        picker: []
      },
      tableData: [],
      currentPage: 1,
      options1: [
        {
          label: "未开始",
          value: "TODO"
        },
        {
          label: "进行中",
          value: "DOING"
        },
        {
          label: "已完成",
          value: "DONE"
        }
      ],
      options2: [
        {
          label: "成功",
          value: "success"
        },
        {
          label: "失败",
          value: "error"
        }
      ],
      pageSize: 10,
      total: 0
    };
  },
  watch: {
    selectValue: {
      handler: function(newV) {
        this.initdata(newV);
      }
    }
  },
  created() {
    this.initdata();
  },
  methods: {
    selectChange(val) {
      this.status = val;
    },
    handleLog(taskId) {
      this.$router.push(`/log/log?id=${taskId}`);
    },
    // 导出
    exportData() {
      axios({
        url: `/api/cloud_log/register/export`,
        method: "GET",
        responseType: "blob"
      })
        .then(response => {
          // 处理文件流响应
          const blob = new Blob([response], {
            type: "application/vnd.ms-excel"
          });
          const url = URL.createObjectURL(blob);
          // 创建一个下载链接，让用户下载文件
          const link = document.createElement("a");
          link.href = url;
          link.click();
          URL.revokeObjectURL(url);
        })
        .catch(err => {
          this.loading = false;
        });
    },
    clickBtn() {
      const inp = document.getElementById("table1");
      inp.click();
    },
    // 解析导入的表格
    handleFileUpload(event) {
      console.log(event.target);
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = e => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        // 在控制台打印解析后的数组
        console.log("rows", jsonData);
        this.$http
          .post(`/api/cloud_log/register/upload`, jsonData)
          .then(res => {
            if (res.success) {
              this.$success("导入成功");
            } else {
              this.$error(res.msg);
            }
          });
      };

      reader.readAsArrayBuffer(file);
    },
    submitForm() {
      this.initdata();
    },
    resetForm() {
      this.form = {
        scheduleStatus: "",
        taskStatus: "",
        keyward: "",
        picker: []
      };
      this.initdata();
    },
    initdata() {
      const {
        scheduleStatus = "",
        taskStatus = "",
        keyward = "",
        picker = []
      } = this.form;
      this.loading = true;
      this.$http
        .post(`/api//cloud_log/register/list`, {
          ips: [...this.selectValue],
          page: this.currentPage,
          limit: this.pageSize,
          scheduleStatus,
          taskStatus,
          keyward,
          startTime: (picker.length && picker[0].getTime()) || null,
          endTime: (picker.length && picker[1].getTime()) || null
        })
        .then(res => {
          if (res.success) {
            this.tableData = res.data.list.map(v => {
              return {
                ...v,
                startTimeStr: moment(v.startTimeStr).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
                endTimeStr: moment(v.endTimeStr).format("YYYY-MM-DD HH:mm:ss")
              };
            });
            this.total = res.data.total;
            this.loading = false;
          } else {
            this.$error(res.msg);
            this.loading = false;
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.initdata();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initdata();
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  padding: 20px 0 0;
}

.el-row {
  padding: 10px 0;
}
</style>
